#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from app.fwmap import fwmap
from app.fwmap import restfulApi
from flask import render_template, request
from flask_restful import Resource
from app.fwmap.view.views import check_table
from app import db
from app.public import ResultJson

########################  展示页面
@fwmap.route('/fwaddindex/<path:position>')
def fwaddindex(position):
    return render_template('fwadd/fwaddindex.html')

# 添加的页面
@fwmap.route('/fwcreate/<path:position>')
def fwcreate(position):
    # 对于 展示页面 position只是用来接受前端的参数， 然后前台分析在发送到API 数据接口
    return render_template('fwadd/fwcreate.html')

# 编辑展示页面
@fwmap.route('/fwedit/<path:position>',endpoint='fwedit')
def fwedit(position):
    return render_template('fwadd/fwedit.html')


######################## 数据接口
# 首页展示， 添加， 删除
class IndexApi(Resource):
    def get(self, tablename, position):
        result = ResultJson()
        if check_table(tablename):
            sql = "select * from {0} where position_id = {1}".format(tablename, position)
            if all([db.session.execute(sql).fetchall(), ]):
                for u in db.session.execute(sql).fetchall():  result.data.append({'id': u.id, 'address': u.address})
        return result.to_json()  # 如果有问题，前台会直接返回接口错误

    def post(self, tablename, position):
        result = ResultJson()
        address = request.form["address"]
        sql = 'select * from {0} where position_id = {1} and address = "{2}"'.format(tablename, position, address)
        if not all([db.session.execute(sql).fetchone()]):
            try:
                sql = 'insert into {0} (address, position_id) VALUES ("{1}",{2})'.format(tablename, address, position)
                db.session.execute(sql)
                db.session.commit()
                result.code = 10000
            except Exception:
                result.code = 10001
        else:
            result.code = 10001
        return result.to_json()

    def delete(self, tablename, position):
        delid = request.form["id"]
        print("delid:    ",delid)
        result = ResultJson()
        if tablename == "outmaps":
            sql = 'select firewalld.id,outmaps.address from firewalld LEFT JOIN outmaps on ' \
                  'firewalld.outaddress = outmaps.id where outmaps.id={0};'.format(
                delid)
        elif tablename == "inmaps":
            sql = 'select firewalld.id,inmaps.address from firewalld LEFT JOIN inmaps on ' \
                  'firewalld.inaddress = inmaps.id where inmaps.id={0};'.format(delid)
        if not all([db.session.execute(sql).fetchone()]):
            result.code = 10000
            sql = 'delete from {0} where id={1}'.format(tablename, delid)
            db.session.execute(sql)
            db.session.commit()
        else:
            result.code = 10001
        return result.to_json()

# 编辑页面渲染加修改
class IndexEdit(Resource):
    def get(self):
        result = ResultJson()
        tablename = request.args["tablename"]
        changeid = request.args["changeid"]
        if check_table(tablename):
            sql = 'select * from {0} where id={1} limit 1'.format(tablename, changeid)
            if all([db.session.execute(sql).fetchone()]):
                result.code = 10000
                for u in db.session.execute(sql).fetchall():  result.data.append({'id': u.id, 'address': u.address})
        return result.to_json()

    def put(self):
        result = ResultJson()
        address = request.form['address']
        changeid = request.form['changeid']
        tablename = request.form['tablename']
        if check_table(tablename):
            sql = 'UPDATE {0} set address = "{1}" WHERE id={2}'.format(tablename, address, changeid)
            result.code = 10000
            db.session.execute(sql)
            db.session.commit()
        return result.to_json()


restfulApi.add_resource(IndexApi, '/fwIndexApi/<tablename>/<position>', endpoint="IndexApi")
restfulApi.add_resource(IndexEdit, '/fwEditApi', endpoint="IndexEdit")
